package com.yjc.rabbitmq.springboot_rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author shkstart
 * @create 2022-08-03 13:01
 */
@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String idRes = correlationData != null ? correlationData.getId() : "";
        if (ack) {
            log.info("交换机已收到id为 {} 的消息", idRes);
        } else {
            log.info("交换机未收到id为 {} 的消息，原因是-->{}", idRes, cause);
        }
    }


    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.error("消息 {},被交换机 {}退回,退回原因：{},路由key：{}",
                new String(returned.getMessage().getBody()), returned.getExchange(), returned.getReplyText(), returned.getRoutingKey());
    }
}
